package com.lemon.smartsafetynew.ui.fragment.monitor;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafetynew.entity.common.DateTypeEnum;
import com.lemon.smartsafetynew.entity.monitor.MonitorStatisticResultVo;
import com.lemon.smartsafetynew.entity.monitor.MonitorTopEntityVo;
import com.lemon.smartsafetynew.net.services.MonitorServices;
import com.lemon.smartsafetynew.ui.widget.marker.MyMarkerView;
import com.lemon.smartsafetynew.util.common.ColorUtil;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Andrew on 2017/8/7.
 */

public class MonitorOverviewFragment extends BaseFragment {

    @Bind(R.id.total_monitor_tv)
    TextView totalMonitorTv;
    @Bind(R.id.abnormal_monitor_tv)
    TextView abnormalMonitorTv;
    @Bind(R.id.normal_monitor_tv)
    TextView normalMonitorTv;

    @Bind(R.id.pie_chart)
    PieChart pieChart;
    @Bind(R.id.normal_tv)
    TextView normalTv;
    @Bind(R.id.abnormal_tv)
    TextView abnormalTv;
    @Bind(R.id.no_info_tv)
    TextView noInfoTv;

    @Bind(R.id.time_format_arrow)
    ImageView timeFormatArrow;
    @Bind(R.id.index_tv)
    TextView indexTv;
    @Bind(R.id.index_last)
    ImageView indexLast;
    @Bind(R.id.time_tv)
    TextView timeTv;
    @Bind(R.id.index_next)
    ImageView indexNext;
    @Bind(R.id.line_chart)
    LineChart lineChart;

    @Bind(R.id.top_one_name)
    TextView topOneName;
    @Bind(R.id.top_two_name)
    TextView topTwoName;
    @Bind(R.id.top_three_name)
    TextView topThreeName;
    @Bind(R.id.time_type_layout)
    LinearLayout timeTypeLayout;
    @Bind(R.id.top_one_count)
    TextView topOneCount;
    @Bind(R.id.top_two_count)
    TextView topTwoCount;
    @Bind(R.id.top_three_count)
    TextView topThreeCount;
    @Bind(R.id.top_one_layout)
    LinearLayout topOneLayout;
    @Bind(R.id.top_two_layout)
    LinearLayout topTwoLayout;
    @Bind(R.id.top_three_layout)
    LinearLayout topThreeLayout;


    private DateTypeEnum date_type = DateTypeEnum.DAY;
    private Date currentDate;
    private Date date;

    @Override
    protected void getBaseArguments() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_monitor_overview;
    }

    @Override
    protected void initViews() {

        // ==== Value ====
        initData();

        // ==== Time UI ====
        timeTv.setText(CommonUtil.getNowTimeStr(date_type));
        if (CommonUtil.compareDate(date, currentDate)) {
            indexNext.setVisibility(View.VISIBLE);
        } else {
            indexNext.setVisibility(View.INVISIBLE);
        }

        initPieChart();
        initLineChart();

        // ======== Get Net Data =========
        MonitorServices.init().getRealTimeMonitorPointAllStatus();

        getReportNetData();

    }

    private void initData() {
        currentDate = CommonUtil.getNowDate();
        date = CommonUtil.getNowDate();
    }

    public static MonitorOverviewFragment newInstance() {

        Bundle args = new Bundle();

        MonitorOverviewFragment fragment = new MonitorOverviewFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @OnClick({R.id.index_next, R.id.index_last, R.id.time_type_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.index_next:
                rightArrowBtnClick();
                break;
            case R.id.index_last:
                leftArrowBtnClick();
                break;
            case R.id.time_type_layout:
                showPopupWindow(view);
                break;

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GET_MONITOR_ALL_STATUS.equals(event.getTag())) { //获得监控点的所有数量，异常个数，正常个数，无数据个数
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    mHUDUtil.hidden();

                    List<Integer> list = (List<Integer>) event.getObj();
                    initOverView(list);

                    // ======== 获取所有的传感器数据 =========
                    MonitorServices.init().getRealTimeMonitorPointAllSensorStatus();

                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                        }
                    });
                }
            }
        } else if (KeyConstants.URL_GET_MONITOR_ALL_SENSOR.equals(event.getTag())) { //获得传感器的所有数量，异常个数，正常个数，无数据个数

            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    List<Integer> list = (List<Integer>) event.getObj();
                    setPieChartData(list);

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }

        } else if ((KeyConstants.URL_GET_MONITOR_ALARM_AVG + DateTypeEnum.DAY.getName()).equals(event.getTag())) { //日报

            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    MonitorStatisticResultVo statisticResultVo = (MonitorStatisticResultVo) event.getObj();
                    showChartDaily(statisticResultVo.getDataList());
                    showSortView(statisticResultVo.getTopList());

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }

        } else if ((KeyConstants.URL_GET_MONITOR_ALARM_AVG + DateTypeEnum.MONTH.getName()).equals(event.getTag())) { //月报

            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    MonitorStatisticResultVo statisticResultVo = (MonitorStatisticResultVo) event.getObj();
                    showChartMonth(statisticResultVo.getDataList());
                    showSortView(statisticResultVo.getTopList());

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }

        } else if ((KeyConstants.URL_GET_MONITOR_ALARM_AVG + DateTypeEnum.YEAR.getName()).equals(event.getTag())) { //年报

            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    MonitorStatisticResultVo statisticResultVo = (MonitorStatisticResultVo) event.getObj();
                    showChartYear(statisticResultVo.getDataList());
                    showSortView(statisticResultVo.getTopList());

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }

        }
    }

    private void initOverView(List<Integer> list) {
        totalMonitorTv.setText(list.get(0) + "");
        abnormalMonitorTv.setText(list.get(1) + list.get(3) + "");
        normalMonitorTv.setText(list.get(2) + "");
    }

    // ======== PieChart ========
    private void initPieChart() {

        pieChart.setNoDataText("无数据");
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        pieChart.setCenterText("监测点状态");
        pieChart.setDrawHoleEnabled(true);
        pieChart.setHoleColor(Color.WHITE);
        pieChart.setTransparentCircleColor(Color.WHITE);
        pieChart.setTransparentCircleAlpha(110);
        pieChart.setHoleRadius(58f);
        pieChart.setTransparentCircleRadius(61f);
        pieChart.setDrawCenterText(true);
        pieChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        pieChart.setRotationEnabled(false);
        pieChart.setHighlightPerTapEnabled(false);

        Legend l = pieChart.getLegend();
        l.setEnabled(false);

        // entry label styling
        pieChart.setEntryLabelColor(Color.WHITE);
        pieChart.setEntryLabelTextSize(12f);

    }

    private void setPieChartData(List<Integer> list) {

        initPieChartLegend(list);

        ArrayList<PieEntry> entries = new ArrayList<>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        for (int i = 1; i < list.size(); i++) {
            entries.add(new PieEntry(list.get(i)));
        }

        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setDrawValues(false);

        // add a lot of colors
        ArrayList<Integer> colors = new ArrayList<>();

        colors.add(Color.parseColor(ColorUtil.pieChartColor[0]));
        colors.add(Color.parseColor(ColorUtil.pieChartColor[1]));
        colors.add(Color.parseColor(ColorUtil.pieChartColor[2]));

        dataSet.setColors(colors);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        pieChart.setData(data);

        // undo all highlights
        pieChart.highlightValues(null);

        pieChart.invalidate();
    }

    private void initPieChartLegend(List<Integer> list) {
        normalTv.setText("正常：" + list.get(2));
        abnormalTv.setText("异常：" + list.get(1));
        noInfoTv.setText("无数据：" + list.get(3));
    }


    // ======== LineChart ========
    private void initLineChart() {

        lineChart.setDrawGridBackground(false);
        lineChart.setNoDataText("无数据");
        // no description text
        lineChart.getDescription().setEnabled(false);

        // enable touch gestures
        lineChart.setTouchEnabled(true);

        // enable scaling and dragging
        lineChart.setDragEnabled(false);
        lineChart.setScaleEnabled(false);
        // mChart.setScaleXEnabled(true);
        // mChart.setScaleYEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(false);

        lineChart.fitScreen();

        // set an alternative background color
        // mChart.setBackgroundColor(Color.GRAY);

        // create a custom MarkerView (extend MarkerView) and specify the layout
        // to use for it
        //TODO MarkView
        MyMarkerView mv = new MyMarkerView(getmContext(), R.layout.custom_marker_view);
        mv.setChartView(lineChart); // For bounds control
        lineChart.setMarker(mv); // Set the marker to the chart

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawZeroLine(false);

        // limit lines are drawn behind data (and not on top)
        leftAxis.setDrawLimitLinesBehindData(true);

        lineChart.getAxisRight().setEnabled(false);

        // add data
        //setLineChartData(24, 1000);

        lineChart.animateX(500);

        // get the legend (only possible after setting data)
        Legend l = lineChart.getLegend();
        l.setEnabled(false);

    }

    /**
     * TODO 这里用addView会更简单一点
     *
     * @param list
     */
    private void showSortView(List<MonitorTopEntityVo> list) {

        if (list == null || list.size() == 0) {
            return;
        }

        List<LinearLayout> viewList = new ArrayList<>();
        viewList.add(topOneLayout);
        viewList.add(topTwoLayout);
        viewList.add(topThreeLayout);

        for (int i = 0; i < viewList.size(); i++) {
            if (i < list.size()) {
                LinearLayout linearLayout = viewList.get(i);
                linearLayout.setVisibility(View.VISIBLE);
                TextView name = (TextView) linearLayout.getChildAt(1);
                TextView count = (TextView) linearLayout.getChildAt(2);
                name.setText(list.get(i).getName());
                count.setText(list.get(i).getCount() + "");
            } else {
                LinearLayout linearLayout = viewList.get(i);
                linearLayout.setVisibility(View.GONE);
            }
        }

    }

    /**
     * 日报
     *
     * @param list
     */
    private void showChartDaily(List<Integer> list) {

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value + "时");
            }
        });
        xAxis.setAvoidFirstLastClipping(true);
        xAxis.setGranularity(1f);

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setGranularity(1f);

        ArrayList<Entry> values = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            float val = list.get(i);
            values.add(new Entry(i, val));
        }

        LineDataSet set1;

        set1 = new LineDataSet(values, "DataSet 1");
        set1.setDrawValues(false);

        // set the line to be drawn like this "- - - - - -"
        set1.enableDashedLine(10f, 5f, 0f);
        set1.enableDashedHighlightLine(10f, 5f, 0f);
        set1.setColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setCircleColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setLineWidth(1f);
        set1.setCircleRadius(3f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.setDrawFilled(true);
        set1.setFormLineWidth(1f);
        set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
        set1.setFormSize(15.f);
        set1.setHighLightColor(Color.TRANSPARENT);

        set1.setFillColor(Color.parseColor(ColorUtil.lineChartColor));

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1); // add the datasets

        // create a data object with the datasets
        LineData data = new LineData(dataSets);

        // set data
        lineChart.setData(data);

        lineChart.invalidate();
    }

    /**
     * 月报
     *
     * @param list
     */
    private void showChartMonth(List<Integer> list) {

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value + "日");
            }
        });
        xAxis.setAvoidFirstLastClipping(true);
        xAxis.setGranularity(1f);

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setGranularity(1f);

        ArrayList<Entry> values = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            float val = list.get(i);
            values.add(new Entry(i + 1, val));
        }

        LineDataSet set1;

        set1 = new LineDataSet(values, "DataSet 1");
        set1.setDrawValues(false);

        // set the line to be drawn like this "- - - - - -"
        set1.enableDashedLine(10f, 5f, 0f);
        set1.enableDashedHighlightLine(10f, 5f, 0f);
        set1.setColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setCircleColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setLineWidth(1f);
        set1.setCircleRadius(3f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.setDrawFilled(true);
        set1.setFormLineWidth(1f);
        set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
        set1.setFormSize(15.f);
        set1.setHighLightColor(Color.TRANSPARENT);

        set1.setFillColor(Color.parseColor(ColorUtil.lineChartColor));

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1); // add the datasets

        // create a data object with the datasets
        LineData data = new LineData(dataSets);

        // set data
        lineChart.setData(data);

        lineChart.invalidate();
    }

    /**
     * 年报
     *
     * @param list
     */
    private void showChartYear(List<Integer> list) {

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value + "月");
            }
        });
        xAxis.setAvoidFirstLastClipping(true);
        xAxis.setGranularity(1f);

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setGranularity(1f);

        ArrayList<Entry> values = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            float val = list.get(i);
            values.add(new Entry(i+1, val));
        }

        LineDataSet set1;

        set1 = new LineDataSet(values, "DataSet 1");
        set1.setDrawValues(false);

        // set the line to be drawn like this "- - - - - -"
        set1.enableDashedLine(10f, 5f, 0f);
        set1.enableDashedHighlightLine(10f, 5f, 0f);
        set1.setColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setCircleColor(Color.parseColor(ColorUtil.lineChartColor));
        set1.setLineWidth(1f);
        set1.setCircleRadius(3f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.setDrawFilled(true);
        set1.setFormLineWidth(1f);
        set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
        set1.setFormSize(15.f);
        set1.setHighLightColor(Color.TRANSPARENT);

        set1.setFillColor(Color.parseColor(ColorUtil.lineChartColor));

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1); // add the datasets

        // create a data object with the datasets
        LineData data = new LineData(dataSets);

        // set data
        lineChart.setData(data);

        lineChart.invalidate();
    }


    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getmContext()).inflate(
                R.layout.popup_report_layout, null);
        // 设置按钮的点击事件
        TextView dayTv = (TextView) contentView.findViewById(R.id.day_report_tv);
        TextView monthTv = (TextView) contentView.findViewById(R.id.month_report_tv);
        TextView yearTv = (TextView) contentView.findViewById(R.id.year_report_tv);

        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        // 设置好参数之后再show
        popupWindow.showAsDropDown(view, -1 * CommonUtil.convertDipOrPx(getmContext(), 40), 0);


        dayTv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                indexTv.setText(((TextView) v).getText());

                date_type = DateTypeEnum.DAY;
                popupWindow.dismiss();
                reportTypeChange();
            }
        });

        monthTv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                indexTv.setText(((TextView) v).getText());

                date_type = DateTypeEnum.MONTH;
                popupWindow.dismiss();
                reportTypeChange();
            }
        });

        yearTv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                indexTv.setText(((TextView) v).getText());

                date_type = DateTypeEnum.YEAR;
                popupWindow.dismiss();
                reportTypeChange();
            }
        });

    }


    /**
     * 报表时间周期发生改变
     */
    private void reportTypeChange() {
        date = CommonUtil.getNowDate();
        requestData(date);
    }

    private void leftArrowBtnClick() {
        date = CommonUtil.calendarDelOne(date_type, date);
        requestData(date);
    }

    private void rightArrowBtnClick() {
        date = CommonUtil.calendarPlusOne(date_type, date);
        requestData(date);
    }

    /**
     * 和当前的时间比较，确定是否有左右键
     *
     * @param mDate
     */
    private void requestData(Date mDate) {

        //========== UI change =======
        timeTv.setText(CommonUtil.dateToTimeStr(mDate, date_type));
        if (CommonUtil.compareDate(mDate, currentDate)) {
            indexNext.setVisibility(View.VISIBLE);
        } else {
            indexNext.setVisibility(View.INVISIBLE);
        }

        //========== http request =======

        getReportNetData();
    }

    // ====== 获取异常指数统计 ======
    private void getReportNetData() {

//        DateTypeEnum typeEnum;

//        switch (date_type) {
//            case DAY:
//                typeEnum = DateTypeEnum.DAY;
//                break;
//            case MONTH:
//                typeEnum = DateTypeEnum.MONTH;
//                break;
//            case YEAR:
//                typeEnum = DateTypeEnum.YEAR;
//                break;
//            default:
//                typeEnum = DateTypeEnum.DAY;
//                break;
//        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        Calendar calendarTarget = Calendar.getInstance();
        calendarTarget.setTime(calendar.getTime());
        calendarTarget.set(Calendar.HOUR_OF_DAY, 0);
        calendarTarget.set(Calendar.MINUTE, 0);
        calendarTarget.set(Calendar.SECOND, 0);

        LemonRequestParams params = new LemonRequestParams("");

        switch (date_type) {
            case DAY:
                params.put("time", CommonUtil.timeToStr(calendarTarget.getTime()));
                break;
            case MONTH:
                //params.put("time", CommonUtil.secondToTimeStr(calendarTarget.getTime().getTime(), DateTypeEnum.DAY));
                params.put("time", CommonUtil.timeToStr(calendarTarget.getTime()));
                break;
            case YEAR:
                //params.put("time", CommonUtil.secondToTimeStr(calendarTarget.getTime().getTime(), DateTypeEnum.DAY));
                params.put("time", CommonUtil.timeToStr(calendarTarget.getTime()));
                break;
            default:
                params.put("time", CommonUtil.timeToStr(calendarTarget.getTime()));
                break;
        }

        //params.put("time", CommonUtil.timeToStr(calendarTarget.getTime()));

        MonitorServices
                .init()
                .getRealTimeMonitorPointAllAlarmAvg(params, date_type);

    }

//    private void chooseTimeType() {
//        new MaterialDialog.Builder(getmContext())
//                .items(R.array.date_array)
//                .itemsCallback(new MaterialDialog.ListCallback() {
//                    @Override
//                    public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
//                        indexTv.setText(text);
//                    }
//                })
//                .show();
//    }


/*
    // ======== HorizontalBarChart ========
    private void initHorizontalBarChart() {
        horizontalBarChart.setDrawBarShadow(false);

        horizontalBarChart.setDrawValueAboveBar(true);

        horizontalBarChart.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        horizontalBarChart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        horizontalBarChart.setPinchZoom(false);

        // draw shadows for each bar that show the maximum value
        // mChart.setDrawBarShadow(true);

        horizontalBarChart.setDrawGridBackground(false);

        XAxis xl = horizontalBarChart.getXAxis();
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
        xl.setDrawAxisLine(true);
        xl.setDrawGridLines(false);
        xl.setGranularity(10f);

        YAxis yl = horizontalBarChart.getAxisLeft();
        yl.setDrawAxisLine(false);
        yl.setDrawGridLines(false);
        yl.setAxisMinimum(0f); // this replaces setStartAtZero(true)
//        yl.setInverted(true);

        YAxis yr = horizontalBarChart.getAxisRight();
        yr.setDrawAxisLine(false);
        yr.setDrawGridLines(false);
        yr.setAxisMinimum(0f); // this replaces setStartAtZero(true)
//        yr.setInverted(true);

        setHorizontalBarChartData(10, 50);

        horizontalBarChart.setFitBars(true);
        horizontalBarChart.animateY(2500);

        horizontalBarChart.getLegend().setEnabled(false);

    }

    private void setHorizontalBarChartData(int count, float range) {

        float barWidth = 9f;
        float spaceForBar = 10f;
        ArrayList<BarEntry> yVals1 = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            float val = (float) (Math.random() * range);
            yVals1.add(new BarEntry(i * spaceForBar, val));
        }

        BarDataSet set1;

        if (horizontalBarChart.getData() != null &&
                horizontalBarChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet)horizontalBarChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            horizontalBarChart.getData().notifyDataChanged();
            horizontalBarChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "DataSet 1");
            set1.setBarShadowColor(Color.parseColor(ColorUtil.pieChartColor[0]));
            set1.setBarShadowColor(Color.parseColor(ColorUtil.pieChartColor[0]));

            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setBarWidth(barWidth);
            horizontalBarChart.setData(data);
        }
    }
*/

}
